﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using MyCode.Tools;

namespace MyCode.Web.Controllers
{
    public class BaseController : Controller
    {
        public ICacheHelper cacheHelper { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var actionUrl = filterContext.ActionDescriptor.DisplayName;//获取Url路径
            if (actionUrl.Contains("LoginController"))
            {
                if (actionUrl.Contains("Index"))
                {
                    //访问的是登录控制器写日 Cookie
                    var key = HttpContext.Session.Id;
                    filterContext.HttpContext.Response.Cookies.Append("sessionID", key);
                    base.OnActionExecuting(filterContext);
                }
                
            }
            else
            {
                base.OnActionExecuting(filterContext);
                //访问的是其他控制器进行验证
                var obj = cacheHelper.GetCache<object>();
                if (obj == null)
                {
                    var url = "/Login/Index";
                    ContentResult Content = new ContentResult();
                    Content.Content = $"<script type='text/javascript'>alert('登陆超时!请重新登陆!');location.href='{url}'</script>";
                    Content.ContentType = "text/html;charset=utf-8;";
                    filterContext.Result = Content;// Redirect(url);
                    return;
                }
            }
        }
    }
}